package cn.zd.demo1.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.zd.demo1.R;
import cn.zd.demo1.data.Fruits;

public class MyViewPageAdapter extends PagerAdapter {
    private List<Fruits> dataList = Fruits.initData;

    private Context context;
    private List<View> imageViews = new ArrayList<>();

    public MyViewPageAdapter(Context context) {
        this.context = context;
        dataList.forEach(fruits -> {
            View convertView = LayoutInflater.from(context).inflate(R.layout.spinner_item,null);
            LinearLayout ly_list_view = convertView.findViewById(R.id.ly_list_view);
            ImageView iv = convertView.findViewById(R.id.iv_img);
            TextView tv_name = convertView.findViewById(R.id.tv_name);
            TextView tv_detail = convertView.findViewById(R.id.tv_detail);
            tv_name.setText(fruits.getName());
            tv_detail.setText(fruits.getDetail());
            iv.setImageResource(fruits.getImg());
            imageViews.add(convertView);
        });
    }
    public Fruits getData(int position) {
        return dataList.get(position);
    }
    public View getView(int position) {
        return imageViews.get(position);
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    // 实例化指定位置页面，并将其添加到容器中
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        // 向Container中添加视图，可自定义
        container.addView(getView(position));
        /**
         *添加的View 和 本方法返回值 将作为 {@link #isViewFromObject(View, Object)} 方法的入参使用，用于判断两者关系
          */
        return getView(position);
    }

    /**
     * 从容器中销毁指定页面
     * @param container The containing View from which the page will be removed.
     * @param position The page position to be removed.
     * @param object The same object that was returned by
     * {@link #instantiateItem(View, int)}.
     */
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(getView(position));
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return getData(position).getName();
    }
}
